package com.white.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.white.bean.FollowView;
import com.white.bean.User;
import com.white.service.FollowService;
import com.white.service.UserService;
import com.white.upload.Upload;
import com.white.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
public class UserController {
    public static final String LOGIN_USER_ID = "LOGIN_USER_ID";
    @Autowired
    Utils utils;
    @Autowired
    FollowService followService;

    /**
     * 登录用户，需要互斥访问
     */
    public static final Hashtable<Long, User> LOGIN_USERS_MAP = new Hashtable<>();
    @Autowired
    UserService userService;

    @GetMapping({"/", "/login"})
    public String loginController() {
        return "login";
    }

    @PostMapping({"/", "/login"})
    @ResponseBody
    public User loginPostController(@RequestParam("name") String name,
                                      @RequestParam("password") String password,
                                      @RequestParam("rememberMe") String rememberMe,
                                      HttpServletResponse response) {
        User user = userService.login(name, password);
        if (user == null) {
            return null;
        }
        if ("true".equals(rememberMe)) {
            /*给用户添加cookie*/
            Cookie cookie = new Cookie(LOGIN_USER_ID, String.valueOf(user.getUserId()));
            /*设置cookie的有效期*/
            cookie.setMaxAge(24 * 60 * 60);
            response.addCookie(cookie);
        }
        LOGIN_USERS_MAP.put(user.getUserId(), user);
        return user;
    }

    @GetMapping("/login.html")
    public String login() {
        return "login";
    }

    @GetMapping("/register.html")
    public String register() {
        return "register";
    }

    @GetMapping("/register")
    public String getRegister() {
        return "register";
    }


    @PostMapping("/register")
    public String registerController(@RequestParam("name") String name,
                                     @RequestParam("password") String password,
                                     @RequestPart("headImage") MultipartFile headImage,
                                     Model model) {
        String path = "/upload/images/" + headImage.getOriginalFilename();
        User user = new User(name, password, path);
        try {
            if (userService.save(user)) {
                Upload upload = new Upload();
                upload.upload(headImage);
                return "/login";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("msg", "用户名重复");
        return "/register";
    }

    @GetMapping("/getUserById/{userId}")
    @ResponseBody
    public User getUserById(@PathVariable("userId") int userId) {
        return userService.getById(userId);
    }

    /**
     * 获取当前登录的用户数据
     * @param loginUserId 登录用户id
     * @return 用户数据
     */
    @GetMapping("/loginUser")
    @ResponseBody
    public User loginUser(@CookieValue(LOGIN_USER_ID) Long loginUserId) {
        User user = LOGIN_USERS_MAP.get(loginUserId);
        /*若缓存中不存在，从数据库中查询*/
        if (user == null) {
            return userService.getById(loginUserId);
        }
        return user;
    }

    @GetMapping("/user/{userId}")
    public String userDetail(@PathVariable("userId") int userId) {
        return "userDetail";
    }


    @GetMapping("/getFollowUser/{userId}")
    @ResponseBody
    public List<Object> getFollowUserByUserId(@PathVariable("userId") Long userId) {
        List<Object> followList = new ArrayList<>();
        List<FollowView> follows = followService.getFollowById(userId);
        for (FollowView follow : follows) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.getById(follow.getAuthorId());
            map.put("follow", follow);
            map.put("user", user);
            followList.add(map);
        }
        return followList;
    }

    @GetMapping("/followUser")
    public String followUser() {
        return "followUser";
    }

    @GetMapping("/setting")
    public String setting() {
        return "setting";
    }

    @GetMapping("/deleteAccount")
    @ResponseBody
    public void deleteAccount(@CookieValue(LOGIN_USER_ID) Long userId) {
        /*清除cookie*/
        Cookie cookie = new Cookie(LOGIN_USER_ID,null);
        cookie.setMaxAge(0);//设置存活时间，“0”即马上消失
        userService.removeById(userId);
        LOGIN_USERS_MAP.remove(userId);
    }



    @PostMapping("/updateAccount/basic")
    @ResponseBody
    public void updateAccountBasic(@CookieValue(LOGIN_USER_ID) Long userId,
                              @RequestParam("name") String name,
                              @RequestParam("password") String password,
                              @RequestParam("email") String email,
                              @RequestParam("address") String address,
                              @RequestParam("tel") String tel,
                              @RequestParam("receive") int receive,
                              @RequestParam("name") String remind) {

        User user = loginUser(userId);
        user.setName(name);
        user.setPassword(password);
        user.setAddress(address);
        user.setTel(tel);
        user.setEmail(email);
        userService.updateById(user);
        LOGIN_USERS_MAP.put(user.getUserId(), user);
    }
    @PostMapping("/updateAccount/me")
    @ResponseBody
    public void updateAccountMe(@CookieValue(LOGIN_USER_ID) Long userId,
                              @RequestParam("sex") String sex,
                              @RequestParam("profile") String profile) {
        User user = loginUser(userId);
        user.setSex(sex);
        user.setProfile(profile);
        userService.updateById(user);
        LOGIN_USERS_MAP.put(user.getUserId(), user);
    }

    @GetMapping("/wallet")
    public String wallet() {
        return "wallet";
    }



    @GetMapping("/withdrawal/{money}")
    @ResponseBody
    public void withdrawal(@CookieValue(LOGIN_USER_ID) Long userId,
                             @PathVariable("money") Double money) {
        User user = loginUser(userId);
        user.setBalance(money);
        userService.updateById(user);
        LOGIN_USERS_MAP.put(user.getUserId(), user);
    }

    @GetMapping("/getUserPage/{page}/{limit}")
    @ResponseBody
    public Object getUserPage(@PathVariable("page") int page,
                           @PathVariable("limit") int limit) {
        Page<User> userPage = new Page<>(page, limit);
        return userService.page(userPage, null);
    }

    @GetMapping("/deleteUserById/{id}")
    @ResponseBody
    public void deleteUserById(@PathVariable("id") int id) {
        userService.removeById(id);
    }


    @PostMapping("/updateUser")
    @ResponseBody
    public void updateUser(@RequestParam("item") String item) {
        User user = utils.jsonToEntry(User.class, item);
        userService.updateById(user);
    }

//    updateReward
    @PostMapping("/updateReward")
    @ResponseBody
    public void updateReward(@CookieValue(LOGIN_USER_ID) Long userId,
                             @RequestParam("rewardProfile") String rewardProfile) {
        User user = new User();
        user.setUserId(userId);
        user.setRewardProfile(rewardProfile);
        userService.updateById(user);
    }

}
